/**
 * 
 */
package manager;

import java.io.Serializable;
import java.util.List;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.AjaxBehaviorEvent;

import utils.ResourceDAORemote;
import dtos.ResourceDTO;

/**
 *         This is the bean responsible for resource operations (performed in
 *         resourceCRUD.xhtml)
 */
@ManagedBean(name = "resourceBean")
@SessionScoped
public class ResourceBean implements Serializable {

	private static final long serialVersionUID = 6214595044162361633L;

	final Logger logger = Logger.getLogger(ResourceBean.class.getName());

	ResourceBundle bundle = ResourceBundle.getBundle(
			"languageSettings.language", FacesContext.getCurrentInstance()
					.getViewRoot().getLocale());

	/**
	 * Bean managing edit fields
	 */
	private ResourceDTO editResourceDTO;
	/**
	 * Bean managing new resource fields
	 */
	private ResourceDTO newResourceDTO;

	@EJB
	private ResourceDAORemote resourceDAO;

	/**
	 * List of resources displayed on the page
	 */
	private List<ResourceDTO> resourceDTOs;

	/**
	 * Radio buttons selecting between resources/techresources
	 */
	private String selectTypeRadio = "1";
	/**
	 * Search key field
	 */
	private String searchKey = "";
	/**
	 * Feedback shown after operations
	 */
	private String feedback = " ";
	/**
	 * Boolean controlling whether to view new resource fields
	 */
	private boolean showNew = false;

	public ResourceBean() {
	}

	/**
	 * Initializes DTOs.
	 */
	@PostConstruct
	public void init() {
		newResourceDTO = new ResourceDTO();
		newResourceDTO.setName("");
		editResourceDTO = new ResourceDTO();
		editResourceDTO.setId(0);
		resourceDTOs = resourceDAO.getAllResources();
	}

	/**
	 * Gets the resources to be shown filtering them by searchKey
	 */
	private void applySearchKey() {
		logger.log(Level.INFO, "filter key: " + searchKey + " returning: "
				+ resourceDTOs);
		if (editResourceDTO.getId() != 0) {
			resourceDTOs.clear();
			resourceDTOs.add(editResourceDTO);
		} else {
			resourceDTOs = resourceDAO.getResourcesByName(searchKey);
		}
	}

	/**
	 * Ajax listener for search field
	 * 
	 * @param e
	 */
	public void applyFilter(AjaxBehaviorEvent e) {
		applySearchKey();
	}

	/**
	 * Delete button action
	 * 
	 * @return "resourceCRUD.xhtml"
	 */
	public String deleteResource() {
		return "resourceCRUD.xhtml";
	}

	/**
	 * Delete button: Deletes the resource given as attribute 'deleteResource'
	 * 
	 * @param event
	 */
	public void performDelete(ActionEvent event) {
		// perform deletion
		ResourceDTO dr = (ResourceDTO) event.getComponent().getAttributes()
				.get("deleteResource");
		if (dr.getRestickets().size() == 0) {
			resourceDAO.deleteResource(dr);
			logger.log(Level.INFO, "performing delete");
			// show confirmation message
			this.feedback = bundle
					.getString("Beans_manager_resourceBean_feedbackdel");
			applySearchKey();
		} else
			feedback = bundle.getString("Beans_manager_resourceBean_feedback");
	}

	/**
	 * Edit button: Marks an entry as editable, displays only that entry
	 * 
	 * @param event
	 */
	public void markForEdit(ActionEvent event) {
		editResourceDTO = new ResourceDTO();
		editResourceDTO.setId(((ResourceDTO) event.getComponent()
				.getAttributes().get("editResource")).getId());
		editResourceDTO.setName(((ResourceDTO) event.getComponent()
				.getAttributes().get("editResource")).getName());
		logger.log(Level.INFO, "id to be edited:" + editResourceDTO.getId());
		showNew = false;
		applySearchKey();
	}

	/**
	 * Save (edit) button: saves the changes made in textfields
	 * 
	 * @param event
	 */
	public void saveEdit(ActionEvent event) {
		// update resource
		logger.log(Level.INFO, "saving edited:" + editResourceDTO.getId() + " "
				+ editResourceDTO.getName());
		// no duplicate
		List<ResourceDTO> rdtos = resourceDAO.getAllResources();
		for (ResourceDTO r : rdtos) {
			if (editResourceDTO.getId() != r.getId()
					&& editResourceDTO.getName().trim()
							.equalsIgnoreCase(r.getName().trim())) {
				logger.log(Level.INFO, "found name");
				feedback = bundle
						.getString("Beans_manager_resourceBean_feedbackdupl");
				return;
			}
		}

		resourceDAO.updateResource(editResourceDTO);
		this.feedback = bundle
				.getString("Beans_manager_resourceBean_feedbacksaved");
		editResourceDTO.setId(0);
		applySearchKey();
	}

	/**
	 * Cancel (edit) button: cancels editing
	 * 
	 * @return "resourceCRUD.xhtml"
	 */
	public String cancelEdit() {
		editResourceDTO.setId(0);
		logger.log(Level.INFO, "caneled editing");
		applySearchKey();
		return "resourceCRUD.xhtml";
	}

	/**
	 * Toggle new fields
	 * 
	 * @param e
	 */
	public void showNewFields(AjaxBehaviorEvent e) {
		logger.log(Level.INFO, "showing new fields");
		showNew = !showNew;
	}

	/**
	 * Inserts new resource if name is unique
	 * 
	 * @param e
	 */
	public void addNewResource(AjaxBehaviorEvent e) {
		logger.log(Level.INFO, "adding new resource");

		List<ResourceDTO> rdtos = resourceDAO.getAllResources();
		for (ResourceDTO r : rdtos) {
			if (newResourceDTO.getName().trim()
					.equalsIgnoreCase(r.getName().trim())) {
				logger.log(Level.INFO, "found name");
				feedback = bundle
						.getString("Beans_manager_resourceBean_feedbackdupl");
				return;
			}
		}
		resourceDAO.insertResource(newResourceDTO);
		logger.log(Level.INFO, "added new resource");
		feedback = bundle
				.getString("Beans_manager_resourceBean_feedbacknewRes");
		newResourceDTO.setName("");
		searchKey = "";
		applySearchKey();
	}

	/**
	 * Resets edit (when resource type is changed)
	 * 
	 * @param e
	 */
	public void resetEdit(AjaxBehaviorEvent e) {
		cancelEdit();
	}

	public ResourceDTO getEditResourceDTO() {
		return editResourceDTO;
	}

	public void setEditResourceDTO(ResourceDTO editResourceDTO) {
		this.editResourceDTO = editResourceDTO;
	}

	public String getSelectTypeRadio() {
		return selectTypeRadio;
	}

	public void setSelectTypeRadio(String selectTypeRadio) {
		this.selectTypeRadio = selectTypeRadio;
	}

	public String getSearchKey() {
		return searchKey;
	}

	public void setSearchKey(String searchKey) {
		this.searchKey = searchKey;
	}

	public ResourceDTO getNewResourceDTO() {
		return newResourceDTO;
	}

	public void setNewResourceDTO(ResourceDTO newResourceDTO) {
		this.newResourceDTO = newResourceDTO;
	}

	public List<ResourceDTO> getResourceDTOs() {
		return resourceDTOs;
	}

	public void setResourceDTOs(List<ResourceDTO> resourceDTOs) {
		this.resourceDTOs = resourceDTOs;
	}

	public String getFeedback() {
		return feedback;
	}

	public void setFeedback(String feedback) {
		this.feedback = feedback;
	}

	public boolean isShowNew() {
		return showNew;
	}

	public void setShowNew(boolean showNew) {
		this.showNew = showNew;
	}

}